package com.sharedlease.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sharedlease.entity.Chat;
import com.sharedlease.entity.Product;
import com.sharedlease.mapper.ChatMapper;
import com.sharedlease.service.ChatService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sharedlease.utils.RedisUtils;
import org.springframework.stereotype.Service;
import redis.clients.jedis.Jedis;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 吴钟富
 * @since 2021-03-27
 */
@Service
public class ChatServiceImpl extends ServiceImpl<ChatMapper, Chat> implements ChatService {
    /**
     * 从redis中根据两个id查询聊天记录
     *
     * @return
     */
    Jedis jedis = RedisUtils.getConnection();

    public List<Chat> getChatsFromRedisByTwoIds(Long id1, Long id2) {
        String chatRecords = jedis.get("chatRecords");
        if (chatRecords == null || chatRecords.length() == 0) {
            return null;
        }
        List<Chat> chatList = JSONObject.parseArray(chatRecords, Chat.class);
        List<Chat> res = new LinkedList<>();
        for (Chat chat : chatList) {
            if (chat != null) {
                Long sourceId = chat.getSourceId();
                Long destId = chat.getDestId();
                if (id1.equals(sourceId) && id2.equals(destId) || id2.equals(sourceId) && id1.equals(destId)) {
                    res.add(chat);
                }
            }
        }
        return chatList;
//        String id = destId.toString();
//        String chatRecords = jedis.hget("chatRecords",id);
//        if (chatRecords==null||chatRecords.length()==0){
//            return null;
//        }
//        Chat chat = JSONObject.parseObject(chatRecords,Chat.class);
//        return  chat;
//
////json转换为list
//        List<Product> products = new ArrayList<Product>();
//        products = JSONObject.parseArray(jedis.get("allProducts"),Product.class);
//        return products;
//
    }

    public List<Chat> getChatsByDestId(Long destId) {
        String chatRecords = jedis.get("chatRecords");
        List<Chat> chatList = JSONObject.parseArray(chatRecords, Chat.class);
        if (chatList == null || chatList.size() == 0) {
            return null;
        }
        List<Chat> res = new LinkedList<>();
        for (Chat chat : chatList) {
            if (chat != null && destId.equals(chat.getDestId())) {
                res.add(chat);
            }

        }
        return res;

    }

    /**
     * 将所有聊天记录存储到redis
     *
     * @param list 所有产品
     */
    public void saveAllChatsToRedis(List<Chat> list) {
        //list转json
        String chats = JSON.toJSON(list).toString();
        //存储到redis
        jedis.set("chatRecords", chats);
    }


}
